<template>
  <el-dropdown
    :hide-timeout="50"
    :show-timeout="70"
    class="mr20"
    trigger="click"
    @command="onLanguageChange"
  >
    <slot :current-lang="state.disabledI18n">
      <div class="layout-navbars-breadcrumb-user-icon">
        <i
          :class="state.disabledI18n === 'en' ? 'icon-fuhao-yingwen' : 'icon-fuhao-zhongwen'"
          :title="$t('layout.user.title1')"
          class="iconfont"
          style="font-size: 20px"
        ></i>
      </div>
    </slot>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          :disabled="state.disabledI18n === 'zh-cn'"
          command="zh-cn"
        >
          简体中文
        </el-dropdown-item>
        <el-dropdown-item
          :disabled="state.disabledI18n === 'zh-tw'"
          command="zh-tw"
        >
          繁体中文
        </el-dropdown-item>
        <el-dropdown-item
          :disabled="state.disabledI18n === 'en'"
          command="en"
        >
          English
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script lang="ts" setup>
import { useI18n } from "vue-i18n";
import { useThemeConfig } from "@/stores/themeConfig";
import { storeToRefs } from "pinia";
import { Local } from "@/utils/storage";
import other from "@/utils/other";
import { useTLocale } from "@/utils/localeUtil";
import { reactive } from "vue";
import { cloneDeep } from "lodash-es";

const { locale } = useI18n();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const tLocale = useTLocale();

const state = reactive({
  disabledI18n: tLocale.acceptLanguage
});

// 初始化组件i18n
const initI18nOrSize = (value: string, attr: string) => {
  (state as any)[attr] = Local.get("themeConfig")[value];
};

// 语言切换
const onLanguageChange = (lang: string) => {
  Local.remove("themeConfig");
  let tempThemeConfig = cloneDeep(themeConfig.value);
  tempThemeConfig.globalI18n = lang;
  Local.set("themeConfig", tempThemeConfig);
  // locale.value = lang;
  // initI18nOrSize("globalI18n", "disabledI18n");
  // other.useTitle();
  // useTLocale().setLanguage(lang);
  location.reload();
};

initI18nOrSize("globalI18n", "disabledI18n");
</script>
